Categories
Node.js Tips

Node.js Tips — Overwrite Files, POST Request, and Run Async Code in Series

Spread the love

As with any kind of app, there are difficult issues to solve when we write Node apps. In this article, we’ll look at some solutions to common problems when writing Node apps.

Overwrite a File Using fs in Node.js

fs.writeFileSync and fs.writeFile both overwrite the file by default.

Therefore, we don’t have to add any extra checks.

Also, we can set the 'w' flag to make sure we write to the file:

fs.writeFileSync(path, content, {
  encoding: 'utf8',
  flag: 'w'
})

We set the option in the 3rd argument.

Defining an Array as an Environment Variable in Node.js

We can set environment variables as a comma-separated string as its value.

Then we can get the string and call split to split the environment variable string with a comma.

For example, we can write:

app.js

const names = process.env.NAMES.split(',');

Then when we run:

NAMES=bar,baz,foo node app.js

Then process.env.NAMES will be 'bar,baz,foo' .

And then we can call split as we did above to convert it to an array.

Make POST Request Using Node.js

We can make a POST request using the http module.

For instance, we can write:

const http = require('http')

const body = JSON.stringify({
  foo: "bar"
})

const request = new http.ClientRequest({
  hostname: "SERVER_NAME",
  port: 80,
  path: "/some-path",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": Buffer.byteLength(body)
  }
})

request.end(body);

We use the http.ClientRequest constructor to create our request.

We specify the hostname which is the hostname.

port is the port.

path is the path relative to the hostname.

method is the request method, which should be 'POST' to make a POST request.

headers have the request headers.

Then we call request.end to make a request with the body , which is the request body.

Then to listen to the request-response, we listen to the response event.

For instance, we can write:

request.on('response', (response) => {
  console.log(response.statusCode);
  console.log(response.headers);
  response.setEncoding('utf8');
  response.on('data', (chunk) => {
    console.log(chunk);
  });
});

We listen to the response event on the request object.

The callback has the response object which is the read stream with the response .

It also has the statusCode to get the status code.

headers have the response headers.

We listen to the data event on the response to get the response in the chunk parameter.

Together, we have:

const http = require('http')

const body = JSON.stringify({
  foo: "bar"
})

const request = new http.ClientRequest({
  hostname: "SERVER_NAME",
  port: 80,
  path: "/some-path",
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Content-Length": Buffer.byteLength(body)
  }
})

request.end(body);

request.on('response', (response) => {
  console.log(response.statusCode);
  console.log(response.headers);
  response.setEncoding('utf8');
  response.on('data', (chunk) => {
    console.log(chunk);
  });
});

Running Async Code in Series

We can use the async module’s series method to run multiple pieces of async code in series.

For instance, we can write:

const async = require('async');

const foo = (callback) => {
  setTimeout(() => {
    callback(null, 'foo');
  }, 5000);
}

const bar = (callback) => {
  setTimeout(() => {
    callback(null, 'bar');
  }, 2000);
}

async.series([
  foo,
  bar
], (err, results) => {
  console.log(results);
});

We have 2 functions foo and bar which runs setTimeout and takes a Node-style callback.

The callback parameter in each function takes an error object and the result.

Then we can pass the functions to the async.series method after putting them in an array.

Since the signature of the functions match with async.series is looking for, we’ll get the results of each function in the results parameter, which is an array.

It has all the results of each function that we passed as the 2nd argument of callback .

This means results is ['foo', 'bar'] .

Set Navigation Timeout with Node Puppeteer

We can set the navigation timeout with the setDefaultNavigationTimeout method.

For instance, we can write:

await page.setDefaultNavigationTimeout(0);

to set the default timeout in milliseconds.

The timeout will affect goBack , goForward , goto , reload , setContent , and waitForNavigation .

Conclusion

We can set the navigation timeout with Puppeteer. To make a POST request, we can use the http.ClientRequest constructor. Also, we can use the async.series method to run functions that run asynchronously in the Node format sequentially. Environment variables are always strings. writeFile and writeFileSync always overwrite files.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *